//
// Created by zpf on 2023/5/15.
//
#include <QCommandLineParser>
#include <QDebug>
#include <utility>
#include "status-notifier-watcher-application.h"
#include "ukui-sni-watcher-config.h"
#include "watcher.h"

StatusNotifierWatcherApplication::StatusNotifierWatcherApplication(int &argc, char **argv,
                                                                   const QString &applicationName)
        : QtSingleCoreApplication(applicationName, argc, argv)
{
    setApplicationVersion(UKUI_SNI_WATCHER_VERSION);
    qApp->setProperty("IS_UKUI_NOTIFICATION_SERVER", true);
    if (!this->isRunning()) {
        connect(this, &QtSingleCoreApplication::messageReceived, [=](QString msg) {
            this->parseCmd(std::move(msg), true);
        });
        Watcher::self();
    }
    parseCmd(arguments().join(" ").toUtf8(), !isRunning());
}

void StatusNotifierWatcherApplication::parseCmd(const QString& msg, bool isPrimary)
{
    QCommandLineParser parser;

    parser.addHelpOption();
    parser.addVersionOption();

    QCommandLineOption quitOption(QStringList()<<"q"<<"quit", tr("Quit ukui-sni-watcher"));
    parser.addOption(quitOption);

    if (isPrimary) {
        const QStringList args = QString(msg).split(' ');
        parser.process(args);
        if (parser.isSet(quitOption)) {
            qApp->quit();
            return;
        }
    }
    else {
        if (arguments().count() < 2) {
            parser.showHelp();
        }
        parser.process(arguments());
        sendMessage(msg);
    }
}

StatusNotifierWatcherApplication::~StatusNotifierWatcherApplication()
{
}
